package com.mojo.concurrent.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock锁示例1
 * <p>synchronized和ReentrantLock的异同
 * 相同点：都能解决线程安全问题
 * 不同点：
 * 1-synchronized的JVM层面的锁，ReentrantLock是API层面的锁
 * 2-synchronized自动释放锁，ReentrantLock可手动释放锁，上锁和释放锁更灵活
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/18 10:37
 */
public class LockDemo1 {
    public static void main(String[] args) {
        Window window = new Window();
        Thread t1 = new Thread(window);
        Thread t2 = new Thread(window);
        Thread t3 = new Thread(window);
        t1.start();
        t2.start();
        t3.start();
    }

    //窗口卖票

}

class Window implements Runnable {
    //1、定义lock实例
    Lock lock = new ReentrantLock();
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            //2、上锁
            lock.lock();
            try {
                Thread.sleep(100);
                if (ticket > 0) {
                    System.out.println("线程" + Thread.currentThread().getName() + "开始卖票" + ticket);
                    ticket--;
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                lock.unlock();
            }
        }
    }
}
